﻿using System;
using System.Xml;
using Web.Constant.Parameter;

// ReSharper disable once CheckNamespace

namespace Web.Config
{
    public static class Set
    {
        public static void Domain(string domain)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(Information.RootWebConfig);
            var xmlNode =
                (XmlElement)
                    xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/rules/rule/action[@url]");
            if (xmlNode != null)
            {
                xmlNode.SetAttribute("url", @"https://" + domain + @":" + Information.HttpsPort + @"/{R:1}");
                xmlDoc.Save(Information.RootWebConfig);
            }
        }

        public static void SSL(Boolean isNeedSSL)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(Information.RootWebConfig);
            var xmlNode =
                (XmlElement)
                    xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/rules/rule[@enabled]");
            if (xmlNode != null)
            {
                xmlNode.SetAttribute("enabled", isNeedSSL.ToString().ToLower());
                xmlDoc.Save(Information.RootWebConfig);
            }
        }
    }

    public static class Get
    {
        public static Boolean CheckDomain(string domain)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(Information.RootWebConfig);
            try
            {
                var xmlNode =
                    (XmlElement)
                        xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/rules/rule/action[@url]");
                if (xmlNode != null)
                {
                    return (xmlNode.GetAttribute("url")).ToLower() !=
                           (@"https://" + domain + @":" + Information.HttpsPort + @"/{R:1}").ToLower();
                }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }

        public static Boolean SSL()
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(Information.RootWebConfig);
            var xmlNode =
                (XmlElement)
                    xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/rules/rule[@enabled]");
            if (xmlNode != null)
            {
                return xmlNode.GetAttribute("enabled").ToLower() == "true";
            }
            return false;
        }
    }
}